package com.longbig.multifunction.helper;

import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * @author Administrator
 * @date 2024/4/24 10:48
 * @description
 */
@Slf4j
public class ZipHelper {

    /**
     * 将给定的目录中的所有文件打包成zip文件，不包括目录本身。
     * @param directoryPath 要打包的目录路径
     * @param zipFilePath 生成的zip文件路径
     * @throws IOException 如果发生I/O错误
     */
    public static void packDirectoryContentsToZip(String directoryPath, String zipFilePath) {
        File directory = new File(directoryPath);

        try (FileOutputStream fos = new FileOutputStream(zipFilePath);
             ZipOutputStream zos = new ZipOutputStream(fos)) {
            File[] files = directory.listFiles();
            if (files != null) {
                for (File file : files) {
                    addFileToZip(file, "", zos);  // 注意初始路径为空字符串
                }
            }
        } catch (Exception e) {
            log.error("packDirectoryContentsToZip error", e);
        }
    }

    /**
     * 递归方法，将文件或文件夹添加到zip文件中。
     * @param fileToAdd 文件或目录
     * @param baseName 压缩文件中的路径
     * @param zos 压缩输出流
     * @throws IOException 如果发生I/O错误
     */
    private static void addFileToZip(File fileToAdd, String baseName, ZipOutputStream zos) throws IOException {
        if (fileToAdd.isHidden()) {
            return; // 跳过隐藏文件和目录
        }
        String entryName = baseName.isEmpty() ? fileToAdd.getName() : baseName + "/" + fileToAdd.getName();
        if (fileToAdd.isDirectory()) {
            File[] children = fileToAdd.listFiles();
            for (File child : children) {
                addFileToZip(child, entryName, zos);  // 递归添加每个子目录和文件
            }
        } else {
            zos.putNextEntry(new ZipEntry(entryName));
            try (FileInputStream fis = new FileInputStream(fileToAdd)) {
                byte[] buffer = new byte[1024];
                int length;
                while ((length = fis.read(buffer)) >= 0) {
                    zos.write(buffer, 0, length);
                }
            }
            zos.closeEntry();
        }
    }

//    public static void main(String[] args) {
//        String sourceDirectoryPath = "./HB_20240424105509";
//        String zipFilePath = "./output.zip";
//
//        try {
//            packDirectoryContentsToZip(sourceDirectoryPath, zipFilePath);
//            System.out.println("Contents of the directory were successfully compressed to ZIP file.");
//        } catch (IOException e) {
//            System.err.println("Error occurred while compressing the contents of the directory: " + e.getMessage());
//        }
//    }

}
